package com.sk.waste.app.activitys;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sk.waste.app.R;

import androidx.appcompat.app.AppCompatActivity;

public class TestWebActivity  extends AppCompatActivity
  {
    private WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_webview_test);

      webView = findViewById(R.id.ac_detail_webview);

      // 1. 配置 WebSettings
      WebSettings webSettings = webView.getSettings();
      webSettings.setJavaScriptEnabled(true); // 【关键】启用JS
      webSettings.setDomStorageEnabled(true); // 【关键】启用DOM存储
      webSettings.setDatabaseEnabled(true);

      // 2. 解决混合内容问题
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
      }

      // 3. 设置一个标准的User-Agent
      webSettings.setUserAgentString("Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36");
      // 4. 设置 WebViewClient
      webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          Log.d("WebView", "页面开始加载: " + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
          super.onPageFinished(view, url);
          Log.d("WebView", "页面加载完成: " + url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
          super.onReceivedError(view, request, error);
          Log.e("WebView", "加载错误: " + error.getDescription() + ", URL: " + request.getUrl());
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
          super.onReceivedHttpError(view, request, errorResponse);
          Log.e("WebView", "HTTP错误: " + errorResponse.getStatusCode() + ", URL: " + request.getUrl());
        }
      });

      // 5. 加载URL
      String url = "https://zc-paimai.taobao.com/zc/notice_detail.htm?project_id=14361255";
      webView.loadUrl(url);
    }

    @Override
    protected void onDestroy() {
      // 防止内存泄漏
      if (webView != null) {
        webView.destroy();
        webView = null;
      }
      super.onDestroy();
    }
  }
